﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using WSS.BLL.User;
using WSS.BLL.Utils;
using WSS.Models.Hosp;
using WSS.Models.User;
using WSS.Pub;
using Newtonsoft.Json.Serialization;

namespace WSS.Web.Controllers
{
    public class UserCenterController : MyController
    {
        //
        // GET: /UserCenter/

        /// <summary>
        /// 用户中心  -  列表 
        /// </summary>
        /// <param name="id">医院ID</param>
        /// <returns></returns>
        [MyAuthorize]
        public ActionResult UserList(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                //ViewBag.MSG = ViewBag.Title = "参数缺失";
                //return View("Error");
                id = AccountCache.CurrentUserInfo.UserInfo.HOSP_ID;
            }

            HOSP_HOSPITAL hosp = BLL.Hospital.HospDB.Instance.GetOne(id);

            ViewBag.HOSP_ID = id;
            ViewBag.HOSPITAL_NAME = hosp.HOSP_NAME;
            return View();
        }

        /// <summary>
        /// 导入用户
        /// </summary>
        /// <param name="id">医院ID</param>
        /// <returns></returns>
        [MyAuthorize]
        public ActionResult ImportUser(string id)
        {
            ViewBag.HOSP_ID = id;
            HOSP_HOSPITAL hosp = BLL.Hospital.HospDB.Instance.GetOne(id);
            ViewBag.HOSPITAL_NAME = hosp.HOSP_NAME;
            return View();
        }


        [MyAuthorize]
        public ContentResult get_hosiptal_content()
        {
            string sql = @"SELECT COUNT(USER_ID) TOTAL_USER ,H.HOSP_ID,H.HOSP_NAME FROM HOSP_HOSPITAL H 
LEFT JOIN USER_USER U ON U.HOSP_ID = H.HOSP_ID AND U.FLAG_LOGIN = 1
GROUP BY H.HOSP_ID,H.HOSP_NAME";

            var list = DB.Select(sql);

            StringBuilder str = new StringBuilder();

            int count = list.Count;

            if (count == 0)
            {
                str.AppendLine("<div class=\"row\">");
                get_add_hospital_html(ref str);
                str.AppendLine("</div>");
                return Content(str.ToString());
            }

            for (int i = 0; i < count; i++)
            {
                StrObjDict dict = list[i];

                str.AppendLine("<div class=\"row\">");

                str.AppendLine("<div class=\"col-md-5 bg01\">");
                str.AppendLine("<span class=\"glyphicon glyphicon-user\"></span>");
                str.AppendFormat("<a href=\"/usercenter/userlist/{0}\">{1}( {2} )</a>", Utils.GetString(dict, "HOSP_ID"), Utils.GetString(dict, "HOSP_NAME"), Utils.GetString(dict, "TOTAL_USER"));
                str.AppendLine("</div>");
                str.AppendLine("<div class=\"col-md-1\"></div>");
                if (i < count - 1)
                {
                    i++;
                    dict = list[i];
                    str.AppendLine("<div class=\"col-md-5 bg02\">");
                    str.AppendLine("<span class=\"glyphicon glyphicon-user\"></span>");
                    str.AppendFormat("<a href=\"/usercenter/userlist/{0}\">{1}( {2} )</a>",
                        Utils.GetString(dict, "HOSP_ID"), Utils.GetString(dict, "HOSP_NAME"),
                        Utils.GetString(dict, "TOTAL_USER"));
                    str.AppendLine("</div>");
                    str.AppendLine("<div class=\"col-md-1\"></div>");
                    str.AppendLine("</div>");
                    continue;
                }

                get_add_hospital_html(ref str);

                str.AppendLine("</div>");
            }

            if (count % 2 == 0)
            {
                str.AppendLine("<div class=\"row\">");
                get_add_hospital_html(ref str);
                str.AppendLine("</div>");
            }

            return Content(str.ToString());
        }

        private void get_add_hospital_html(ref StringBuilder str)
        {
            str.AppendLine("<div class=\"col-md-5 bg03\" style='text-align:center;'>");
            str.AppendLine("<span class='glyphicon glyphicon-plus-sign'></span><small><a href=\"javascript:void(0)\" onclick='add()'>添加医院</a></small>");
            str.AppendLine("</div>");
            str.AppendLine("<div class=\"col-md-1\"></div>");
            str.AppendLine("</div>");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [MyAuthorize]
        public ActionResult List(string id)
        {
            User user = new User(id);

            var param = new StrObjDict();

            var username = Request.Req("username");
            if (!username.IsNullOrEmpty())
            {
                param.Merger(new { WHERE_CLAUSE = "USER_NAME LIKE '%" + username + "%'" });
            }

            param.Merger(new { ORDER_BY_CLAUSE = " USER_ID DESC" });

            var data = user.GetList(param);

            return this.MyJson(Paginator.Page<USER_USER>(data));
        }


        public ActionResult AddUser(USER_USER usermodel)
        {
            return _SaveUser(usermodel, true);
        }
        public ActionResult UpdateUser(USER_USER usermodel)
        {
            return _SaveUser(usermodel, false);
        }
        private ActionResult _SaveUser(USER_USER usermodel, bool is_add)
        {
            if (usermodel.HOSP_ID.IsNullOrEmpty())
            {
                return this.MyJson(false, "医院ID（HOSP_ID）参数没有值");
            }
            if (usermodel.USER_NO.IsNullOrEmpty())
            {
                return this.MyJson(false, "工号不允许为空");
            }
            if (usermodel.USER_NAME.IsNullOrEmpty())
            {
                return this.MyJson(false, "姓名不允许为空");
            }
            if (is_add)
            {
                usermodel.FLAG_MAIL = 0;
                usermodel.FLAG_PHONE = 0;
                usermodel.USER_PIC = "default.jpg";
                usermodel.USER_PWD = BLL.Utils.MD5.MD5Encrypt("123456", 32);
                usermodel.USER_ID = BLL.Xt.XhbManager.Instance.GetXh(usermodel.GetTableName());
                new User(usermodel.HOSP_ID).Insert(usermodel);
                return this.MyJson(true, "新增成功");
            }
            else
            {
                var instance = new User(usermodel.HOSP_ID);
                var edituser = instance.GetOne(usermodel.USER_ID, usermodel.USER_NO);
                if (edituser != null)
                {
                    usermodel.FLAG_MAIL = edituser.FLAG_MAIL;
                    usermodel.FLAG_PHONE = edituser.FLAG_PHONE;
                    usermodel.USER_PIC = edituser.USER_PIC;

                    usermodel.USER_PWD = edituser.USER_PWD;
                }


                new User(usermodel.HOSP_ID).Update(usermodel);
                return this.MyJson(true, "编辑成功");
            }


        }

        /// <summary>
        /// 用户信息设置修改（个人设置）
        /// </summary>
        /// <param name="usermodel"></param>
        /// <returns></returns>
        [MyAuthorize]
        public ActionResult SaveUserInfo(USER_USER usermodel)
        {
            var instance = new User(usermodel.HOSP_ID);
            var edituser = instance.GetOne(usermodel.USER_ID, usermodel.USER_NO);
            if (edituser != null)
            {
                usermodel.FLAG_MAIL = edituser.FLAG_MAIL;
                usermodel.FLAG_PHONE = edituser.FLAG_PHONE;
                usermodel.FLAG_LOGIN = edituser.FLAG_LOGIN;
                usermodel.USER_PWD = edituser.USER_PWD;
            }
            instance.Update(usermodel);

            UpdateAccountCache(usermodel);

            return this.MyJson(true, "修改成功");
        }

        /// <summary>
        /// 修改用户头像
        /// </summary>
        /// <returns></returns>
        [MyAuthorize]
        public string UploadUserAvatar(string imgName)
        {
            try
            {
                string SqlStr = "update USER_USER set USER_PIC='" + imgName + "' where USER_ID='" + AccountCache.UserId + "'";
                DB.Execute(SqlStr);

                UpdateAccountCache();

                return "1";
            }
            catch
            {
                return "0";
            }
        }


        public ActionResult CheckImportUserFile()
        {
            var filename = Request.Req("filename");
            var hospitalid = Request.Req("hospitalid");

            if (filename.IsNullOrEmpty())
            {
                return this.MyJson(false, "缺少参数:文件名");
            }
            if (hospitalid.IsNullOrEmpty())
            {
                return this.MyJson(false, "缺少参数:医院ID");
            }


            try
            {
                BLL.User.UserImport imp = new UserImport(filename, hospitalid);

                return this.MyJson(true, "导入成功");
            }
            catch (Exception exception)
            {

                return this.MyJson(false, exception.Message);
            }
        }

        /// <summary>
        /// 验证email
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        [MyAuthorize]
        public JsonResult VerifyEmail(string email)
        {

            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string subject = "验证Email";
            string content = "赶快点击下面的链接验证你的E-mail吧：\r\n" +
                             "http://localhost:800//usercenter/activeEmail?u=" + MD5.MD5Encrypt(AccountCache.UserId) + "&t=" + ts.Ticks + "" +
                             "\r\n此链接有效期为两个小时，请在两小时内点击链接进行验证";
            Email.Send(subject, content, email);

            string sqlStr = "update USER_USER set user_email='" + email + "' where USER_ID='" + AccountCache.UserId + "'";
            DB.Execute(sqlStr);

            UpdateAccountCache();

            return this.Json("1");
        }
        /// <summary>
        /// 激活邮箱
        /// </summary>
        /// <returns></returns>
        [MyAuthorize]
        public ActionResult ActiveEmail(string u, long t)
        {
            //验证该链接是否是当前登录用户创建
            string curUserNo = AccountCache.CurrentUserInfo.UserId;
            if (MD5.MD5Encrypt(curUserNo) == u)
            {
                //验证链接是否过期
                TimeSpan curTime = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                TimeSpan differ = new TimeSpan(curTime.Ticks - t);
                //链接有效时间为2小时
                if (differ.Hours > 2)
                {
                    ViewBag.Email = AccountCache.CurrentUserInfo.UserInfo.USER_EMAIL;
                    ViewBag.VerityResult = "timeout";
                }
                else
                {
                    string sqlStr = "update USER_USER set FLAG_MAIL=1 where USER_ID='" + u + "'";
                    DB.Execute(sqlStr);

                    UpdateAccountCache();

                    ViewBag.VerityResult = "success";
                }
                return View("VerityEmail");
            }
            else
            {
                return RedirectToAction("Login", "Login");
            }
        }

        /// <summary>
        /// 原密码是否匹配
        /// </summary>
        /// <returns></returns>
        [MyAuthorize]
        public string CheckOldPwd(string pwd)
        {
            if (MD5.MD5Encrypt(pwd, 32) == AccountCache.CurrentUserInfo.UserInfo.USER_PWD)
            {
                return "1";
            }
            else
            {
                return "0";
            }
        }
        /// <summary>
        /// 修改用户头像
        /// </summary>
        /// <returns></returns>
        [MyAuthorize]
        public string UpdateUerPwd(string pwd)
        {
            try
            {
                string SqlStr = "update USER_USER set user_pwd='" + MD5.MD5Encrypt(pwd, 32) + "' where USER_ID='" + AccountCache.UserId + "'";
                DB.Execute(SqlStr);

                UpdateAccountCache();

                return "1";
            }
            catch
            {
                return "0";
            }
        }
        /// <summary>
        /// 修改cache
        /// </summary>
        /// <param name="usermodel"></param>
        public void UpdateAccountCache(USER_USER usermodel = null)
        {
            if (usermodel == null)
            {
                USER_USER CurUserInfo = this.AccountCache.CurrentUserInfo.UserInfo;
                usermodel = new User(CurUserInfo.HOSP_ID).GetOne(CurUserInfo.USER_ID, CurUserInfo.USER_NO);
            }
            BLL.Account.OnlineHelper _OnlineHelper = new BLL.Account.OnlineHelper();
            _OnlineHelper.UpdateUserInfo(this.AccountCache.CurrentUserInfo.Guid.ToString(), usermodel);
        }

    }
}
